<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('user');
        
        $activeResource=$this->getRequest()->getControllerName();
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Users'));
        
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    public function indexAction()
    {
        $this->view->username='';
        $this->view->avatar='';
        $this->view->description='';
        
        $user=$this->getInvokeArg('bootstrap')->getResource('user');
        
        if ($user->isRegistered())   
        { 
            $this->view->username=$user;
            $this->view->avatar=$user->getAvatar();
            $this->view->description=$user->getDescription();
        } else 
        {
            $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
    }

    /**
     * Authentication action
     *
     */
    public function loginAction()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Authorization'));
        
        $user=$this->getInvokeArg('bootstrap')->getResource('user');
            
        if (!$user->isRegistered())   
        {     
            $form=new Application_Form_Login();
            
            Zend_Registry::set('authForm',$form);
            
            $request=$this->getRequest();
            
            if ($request->isPost())
            {
                if ($form->isValid($request->getPost()))
                {
                    $auth=new Application_Model_UserAuth();
                    
                    if ($auth->authenticate($form->getValue('login'),$form->getValue('password')))
                    {
                        $auth->saveUserSession();
                 //       $this->_response->setRedirect('/'); 
                 
                        $userTbl=new Application_Model_UserDb();
                        $userObj=$userTbl->fetchUserByLogin($form->getValue('login'));
                        
                        $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Hello').' '.$userObj.' !');
                 //       return $this->_helper->redirector('index');
                        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('user'));
                    }
                }
                
                $this->view->message=Zend_Registry::get('locale')->_('Authentication failed');
            }
        }
    }
    
    /**
     * Logout action
     *
     */
    public function logoutAction()
    {
        $auth=new Application_Model_UserAuth();
        
        if ($auth->isAuthenticated())
        {
            $auth->destroyUserSession();
        }
                
        $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl()); 
    }
    
    /**
     * Registration action
     *
     */
    public function registerAction()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        if (!Zend_Registry::get('user')->canPost() || (Zend_Registry::get('user')->isRegistered() && !Zend_Registry::get('user')->canManage()))
        {
            return $this->_helper->redirector('index');
        }
        
        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Registration'));
        
        $form=new Application_Form_Register();
        
        $request=$this->getRequest();
        
        if ($request->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                $user=array(
                    'login' => $form->getValue('login'),
                    'password' => Application_Model_User::crypt_password($form->getValue('password')),
                    'email' => $form->getValue('email'),
                    'nicename' => $form->getValue('nicename'),
                    'role' => Application_Model_UserRoles::getUserRole(),
                    'status' => Application_Model_UserStatuses::getDefaultStatus(),
                    'meta' => array(
                                'register_tstamp' => time(),
                                'user_key' => Application_Model_UserConfirm::randomChars()
                              )
                );
                
                $userObj=new Application_Model_User($user);
                
                $userTbl=new Application_Model_UserDb();
                $uid=$userTbl->save($userObj);
                
                $userObj->id=$uid;
                
                Application_Model_UserConfirm::sendConfirmMessage($userObj);
                
                $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('You\'ve been registered successfully'));
            //    return $this->_helper->redirector('index');
                return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
            }
            
            $this->view->message=Zend_Registry::get('locale')->_('Registration failed');
        }
        
        $this->view->form=$form;
    }
    
    /**
     * User E-Mail confirmation action
     *
     */
    public function confirmAction()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $user=Zend_Registry::get('user');
        
        $key=$this->_getParam('key');
        
        if (!empty($key))
        {
            $success=Application_Model_UserConfirm::do_confirm($key);
            
            if ($success) $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Your account activated'));
        } elseif ($user->isRegistered() && $user->isNotActive())
        {
            Application_Model_UserConfirm::sendConfirmMessage($user);
            
            $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Confirmation message sent'));
        }

     //   return $this->_helper->redirector('index');
        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
    }
    
    /**
     * Password recovery action
     *
     */
    public function recoverAction()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $user=Zend_Registry::get('user');
        
        if ($user->isRegistered())
        {
            return $this->_helper->redirector('index');
        }
        
        $form=new Application_Form_Recover();
        
        $request=$this->getRequest();
        
        $key=$this->_getParam('key');
        
        if (!empty($key))
        {
            $success=Application_Model_UserRecover::do_recover($key);
            
            if ($success) $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Your new password sent to your E-Mail'));
            
            return $this->_helper->redirector('index');
        } elseif ($request->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                $userTbl=new Application_Model_UserDb();
                $userObj=$userTbl->fetchUserByLogin($form->getValue('login'));
                
                Application_Model_UserRecover::sendRecoveryMessage($userObj);
       
                $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Recovery message sent to your E-Mail'));
                
                return $this->_helper->redirector('index');
            }
        }
        
        $this->view->form=$form;
    }
    
    /**
     * User profile edit action
     *
     */
    public function editAction()
    {
        $activeUser=Zend_Registry::get('user');
        
        $key=(int) $this->_getParam('key');
        
        $userTbl=new Application_Model_UserDb();
        
        if (!empty($key) && $activeUser->canManage())
        {  
            $user=$userTbl->fetchUserById($key);
        } elseif (empty($key))
        {
            $user=$activeUser;
        } else 
        {
            return $this->_helper->redirector('index');
        }
        
        if ($user->isRegistered() && !$user->isBlocked())
        {
            $form=new Application_Form_Profile($user);
            
            $request=$this->getRequest();
            
            if ($request->isPost())
            {
                if ($form->isValid($request->getPost()))
                {
                    $user->nicename=$form->getValue('nicename');
                    
                    $new_password=$form->getValue('password');
                    if (!empty($new_password))
                    {
                        $user->password=Application_Model_User::crypt_password($new_password);
                    }
                    
                    $user->email=$form->getValue('email');
                    
                    if ($activeUser->canManage())
                    {
                        $user->role=$form->getValue('role');
                    }
                    
                    if ($form->avatar->receive())
                    {
                        $avatar = $form->avatar->getFileName(null,false);
                        
                        if (!empty($avatar))
                        {
                            $user->setAvatar($avatar);
                        }
                    }
                    
                    $user->setDescription($form->getValue('description'));
                    
                    $userTbl->save($user);
                    
                    $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Profile was updated'));
                    
                //    return $this->_helper->redirector->gotoRoute(array('key'=>$user->id),'userView');
                    return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('user/edit/'.$user->id));
                }
                
                $this->view->message=Zend_Registry::get('locale')->_('Profile was not updated');
            }
            
            $this->view->form=$form;
        } else 
        {
            return $this->_helper->redirector('index');
        }
    }
    
    /**
     * User view action
     *
     */
    public function viewAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $key=(int) $this->_getParam('key');
        
        if (empty($key))
        {
            return $this->_helper->redirector('index');
        }
        
        $userTbl=new Application_Model_UserDb();
        $userObj=$userTbl->fetchUserById($key);
        
        if (!$userObj->isRegistered())
        {
            return $this->_helper->redirector('index');
        }
        
        $this->view->username=$userObj;
        $this->view->avatar=$userObj->getAvatar();
        $this->view->description=$userObj->getDescription();
    }
    
    /**
     * Users list action
     *
     */
    public function listAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $key=(int) $this->_getParam('key');
        
        $userTbl=new Application_Model_UserDb();

        list($users,$paginator)=$userTbl->getUsersPage($key,5);
        
        $this->view->users=$users;
        $this->view->paginator=$paginator;
    }
    
    /**
     * User delete action
     *
     */
    public function deleteAction()
    {
        $key=(int) $this->_getParam('key');
        
        if (empty($key) || !Zend_Registry::get('user')->canManage())
        {
            return $this->_helper->redirector('index');
        }
        
        $userTbl=new Application_Model_UserDb();
        $user=$userTbl->fetchUserById($key);
        
        if (!$user->isRegistered())
        {
            return $this->_helper->redirector('index');
        }

        // we don't want to delete user account from database, that why we just block it
        $user->status=Application_Model_UserStatuses::getBlockedStatus();
        
        $userTbl->save($user);
        
        $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('User was deleted'));
     // return $this->_helper->redirector('list');
        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('user/list'));
        
    }
}

